#!/bin/bash

# Provide source directive to shellcheck.
# shellcheck source=meta-facebook/meta-yosemite4/recipes-phosphor/state/phosphor-state-manager/power-cmd
source /usr/libexec/phosphor-state-manager/power-cmd
CHASSIS_ID=$1

CHASSIS_BUS=$(($1 - 1))
IO_EXP_P0_PWRGD_R_OUT=18
GPIOCHIP_IO_EXP_HOST_POWER_STATUS=$(basename "/sys/bus/i2c/devices/$CHASSIS_BUS-0023/"*gpiochip*)

get_host_status() {
    if ! host_status=$(gpio_get "$GPIOCHIP_IO_EXP_HOST_POWER_STATUS" "$IO_EXP_P0_PWRGD_R_OUT"); then
        echo "Failed to get host status"
        exit 1
    fi
}

get_host_status

if [ "$host_status" == "$STATE_ON" ]
then
    echo "Already host$1 power on."
    exit 0;
fi

# Need to ensure that the mctp connection is complete so that pldmtool can set up successfully.
/usr/libexec/phosphor-state-manager/wait-until-mctp-connection-done "$CHASSIS_ID"

# Set state effecter state: Entity ID 0x0000 for host power control, 0x1 for power on
EID=$(($1*10))
pldmtool raw -d 0x80 0x02 0x39 0x00 0x00 0x01 0x00 0x01 -m "$EID"

# Host power ON will trigger the BIC to configure the server board CPLD register and set the power sequence.
# Power Sequence:
#   - Set PLAT_PLDM_HOST_PWR_CTRL_DEFAULT to 0xFF
#   - Set PLAT_PLDM_HOST_PWR_BTN_LOW to 0xFE
#   - Sleep for 1 second
#   - Set PLAT_PLDM_HOST_PWR_CTRL_DEFAULT back to 0xFF

# Wait for the host to power on
sleep 2s

get_host_status

if [ "$host_status" == "$STATE_ON" ]
then
    echo "Host$1 power on success"
    exit 0;
else
    msg="Failed to set host$1 power on"
    echo "${msg}"
    add_sel "${msg}"
    exit 1
fi
